﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using Oracle.Read;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(2)]
public class LoopLexer : BaseLexer
{
    public override bool Check()
       => Regex.IsMatch(Txt, "^(FOR\\s|LOOP|WHILE)");
    protected override BaseCodeEntity Run()
    {
        var entity = new LoopCodeEntity();
        var txt = Txt;
        var head = txt[..txt.IndexOf('÷')].Trim();
        var list = txt.TrimSplit('÷')[1..^1].ToList();
        if (head.StartsWith("FOR "))
        {
            var idx = Regex.Match(head, "FOR\\s(.*?)\\sIN").Result("$1").Trim();
            var range = Regex.Match(head, "\\sIN(.*)\\sLOOP").Result("$1").Trim();
            //TODO Idx 放到变量定义中
            entity.Idx = idx;
            entity.Condition = SqlFactory.Create(range).Execute();
        }
        else if (head.StartsWith("WHILE"))
        {
            var con = Regex.Match(head, "WHILE(.*)LOOP").Result("$1").Trim();
            entity.Condition = SqlFactory.Create(con).Execute();
        }
        var reader = new SqlLineRead();
        reader.Read(list);
        while (reader.HasNext)
        {
            entity.Body.Add(SqlFactory.Create(reader.Next).Execute());
        }
        return entity;
    }
}
